﻿using System;
using Microsoft.Xna.Framework;
using WindowsGame.Library;
using WindowsGame.Manager;
using WindowsGame.Static;
using WindowsGame.Library.Logger;

namespace WindowsGame
{
	/// <summary>
	/// GameManager is responsible for managing all game actions.
	/// </summary>
	public interface IGameManager
	{
		void Initialize(Game game, GraphicsDeviceManager graphics);
		void LoadContent();
		void UnloadContent();
		void Update(GameTime gameTime);
		void Draw();
		void Exit();
	}

	public class GameManager : IGameManager
	{
		private readonly IDeviceManager deviceManager;
		private readonly IScreenManager screenManager;
		private readonly IGameLogger logger;

		public GameManager(IDeviceManager deviceManager, IScreenManager screenManager, IGameLogger logger)
		{
			this.deviceManager = deviceManager;
			this.screenManager = screenManager;
			this.logger = logger;
		}

		// Initialize game, graphics and logger.
		public void Initialize(Game game, GraphicsDeviceManager graphics)
		{
			logger.Initialize();
			EngineInitialize(game, graphics);
		}

		// Load all content.
		public void LoadContent()
		{
			screenManager.LoadContent();
		}

		// Unload all content.
		public void UnloadContent()
		{
			screenManager.UnloadContent();
		}

		// Update each screen.
		public void Update(GameTime gameTime)
		{
			screenManager.Update(gameTime);
		}

		// Draw each screen.
		public void Draw()
		{
			screenManager.Draw();
		}

		// Exit game.
		public void Exit()
		{
			GameFactory.Release();
		}

		private void EngineInitialize(Game game, GraphicsDeviceManager graphics)
		{
			Engine.Initialize(game, graphics, logger, null, Constants.CONTENT_MANAGER_DIRECTORIES);

			Engine.Game.IsFixedTimeStep = deviceManager.DeviceFactory.IsFixedTimeStep;
			Engine.Game.IsMouseVisible = deviceManager.DeviceFactory.IsMouseVisible;
			Engine.Game.TargetElapsedTime = TimeSpan.FromTicks(deviceManager.DeviceFactory.TargetElapsedTime);

			Engine.GraphicsManager.PreferredBackBufferWidth = deviceManager.DeviceFactory.PreferredBackBufferWidth;
			Engine.GraphicsManager.PreferredBackBufferHeight = deviceManager.DeviceFactory.PreferredBackBufferHeight;
			Engine.GraphicsManager.IsFullScreen = deviceManager.DeviceFactory.IsFullScreen;
			Engine.GraphicsManager.ApplyChanges();
		}
	}
}